package com.cuit.zuke.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.zuke.product.listener.GoodsListener;
import com.cuit.zuke.product.mapper.GoodsMapper;
import com.cuit.zuke.product.model.entity.Goods;
import com.cuit.zuke.product.model.entity.Stock;
import com.cuit.zuke.product.model.vo.GoodsExVO;
import com.cuit.zuke.product.service.GoodsService;
import com.cuit.zuke.product.service.StockService;
import com.cuit.zuke.product.util.FileUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private StockService stockService;

    @Override
    @Cacheable(value = "goods")
    public Page<Goods> selectPage(Page<Goods> page1, QueryWrapper<Goods> wrapper) {
        return baseMapper.selectPage(page1,wrapper);
    }

    /**
     * 更新商品上线状态
     * @param id
     * @param status
     */
    @Override
    @CacheEvict(value = "goods", allEntries = true)   //清空缓存内容
    public void updateStatus(Long id, Integer status) {
        Goods goods = baseMapper.selectById(id);
        goods.setGoodsStatus(status.byteValue());
        goods.setUpdateTime(new Date());
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_id",goods.getGoodsId());
        baseMapper.update(goods,goodsQueryWrapper);
    }

    /**
     * 导出商品excel文件
     * @param response
     */
    @Override
    public void exportGoodsData(HttpServletResponse response) {
        // 设置以下载方式打开
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String filename = "goods";
        response.setHeader("Content-disposition","attachment;filename="+filename+".xlsx");

        // 查询数据库
        List<Goods> goodsList = baseMapper.selectList(null);

        // goods -> goodsExVO
        List<GoodsExVO> goodsExVOList = new ArrayList<>(goodsList.size());
        for (Goods goods : goodsList) {
            GoodsExVO goodsExVO = new GoodsExVO();
            Integer goodsType = goods.getGoodsType();
            Byte goodsStatue = goods.getGoodsStatus();
            if (goodsType == 1){
                goodsExVO.setGoodsType("零食");
            }else if (goodsType == 2){
                goodsExVO.setGoodsType("地方特产");
            }else {
                goodsExVO.setGoodsType("旅游纪念品");
            }
            if(goodsStatue == 0){
                goodsExVO.setGoodsStatus("未上线");
            }else{
                goodsExVO.setGoodsStatus("已上线");
            }
            goodsExVO.setGoodsId(goods.getGoodsId());
            goodsExVO.setGoodsName(goods.getGoodsName());
            goodsExVO.setGoodsPrice(goods.getGoodsPrice());
            goodsExVO.setGoodsDescript(goods.getGoodsDescript());
            goodsExVO.setGoodsImage(goods.getGoodsImage());
            goodsExVOList.add(goodsExVO);
        }
        // 写excel
        try {
            EasyExcel.write(response.getOutputStream(), GoodsExVO.class)
                    .sheet("goods").doWrite(goodsExVOList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel文件
     * @param file
     */
    @Override
    @CacheEvict(value = "goods", allEntries = true)   //清空缓存内容
    public void importGoodsFile(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),GoodsExVO.class,new GoodsListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新商品带图片
     * @param goods
     * @return
     */
    @Override
    @CacheEvict(value = "goods", allEntries = true)   //清空缓存内容
    public boolean updateGoodsAndImgFile(Goods goods,MultipartFile imgFile) throws IOException {

        // 保存图片并返回生成的图片名
        String fileName = FileUtil.saveFile(imgFile, new ApplicationHome(this.getClass()));
        goods.setGoodsImage(fileName);
        goods.setUpdateTime(new Date());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goods.getGoodsId());
        int update = baseMapper.update(goods, queryWrapper);
        if(update > 0){
            return true;
        }
        return false;
    }

    /**
     * 更新商品不带图片
     * @param goods
     * @return
     */
    @Override
    @CacheEvict(value = "goods", allEntries = true)   //清空缓存内容
    public boolean updateGoods(Goods goods) {
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_id",goods.getGoodsId());
        int update = baseMapper.update(goods, goodsQueryWrapper);
        if(update > 0){
            return true;
        }
        return false;
    }

    @Override
    @CacheEvict(value = "goods", allEntries = true)   //清空缓存内容
    public boolean deleteById(Long id) {
        int i = baseMapper.deleteById(id);
        // 删除stock中对应的商品
        QueryWrapper<Stock> queryWrapper = new QueryWrapper();
        queryWrapper.eq("goodsId",id);
        List<Stock> stockList = stockService.list(queryWrapper);
        for (Stock stock : stockList) {
            QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();
            stockQueryWrapper.eq("goodsId",stock.getGoodsId());
            stockService.remove(stockQueryWrapper);
        }
        return i>0;
    }

    @Override
    @CachePut(value = "goods")
    public void add(Goods goods) {
        baseMapper.insert(goods);
    }

    /**
     * 根据goodsId获取goodsName
     */
    public String getGoodsName(Long id){
        Goods goods = baseMapper.selectById(id);
        return goods.getGoodsName();
    }

}
